const Parse = require('parse/node')
const appInfo = require('./appinfo')
const { signJsapiTicket } = require('./wxsign')

let AccessToken = { expiredAt: new Date().getTime() }

Parse.Cloud.define('wxConfig', function (req, res) {
  _wxConfig(req.params.key).then(data => {
    console.log('wxconfig:', data)
    data.appId = appInfo.AppID
    res.success(data)
  }).catch(err => res.success(err))
})

Parse.Cloud.define('getJsapiTicket', function (req, res) {
  _wxGetAccessToken().then(() => {
    if (AccessToken.expiredAt - 10000 > new Date().getTime()) {
      res.success({ticket: AccessToken.jsapiTicket})
    } else {
      _wxGetTicket().then(() => {
        res.success({ticket: AccessToken.jsapiTicket})
      })
    }
  })
})

Parse.Cloud.define('wxAccessToken', function (req, res) {
  _wxGetAccessToken().then(data => res.success(data)).catch(err => res.error(err))
})

function _wxGetTicket () {
  var url = `https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=${AccessToken.access_token}&type=jsapi`
  return Parse.Cloud.httpRequest({ url })
    .then(function (httpResponse) {
      var res = JSON.parse(httpResponse.text)
      console.log(res)
      return (AccessToken.jsapiTicket = res.ticket)
    }, function (httpResponse) {
      console.error('Request <wxGetTicket> failed with response code ' + httpResponse.status)
    })
}

function _wxConfig (key, data) {
  return new Promise(resolve => {
    _wxGetAccessToken().then(() => {
      console.log('return from get access token')
      resolve(_wxGetSig(key))
    })
  })
}

function _wxGetSig (url) {
  url = url || 'http://wx.zhiyaohaodongxi.com/'
  var sig = signJsapiTicket(AccessToken.jsapiTicket, url)
  console.log('signature:', sig)
  return sig
}

function _wxGetAccessToken () {
  return new Promise((resolve, reject) => {
    console.log(appInfo)
    var url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appInfo.AppID}&secret=${appInfo.AppSecret}`
    console.log(new Date().getTime(), AccessToken.expiredAt - 5000, new Date().getTime() < AccessToken.expiredAt - 5000)
    if (new Date().getTime() < AccessToken.expiredAt - 5000) {
      console.log(`access token not expired`)
      return resolve({appId: AccessToken.AppID, access_token: AccessToken.access_token})
    } else {
      console.log(`try to get new access token`)
      Parse.Cloud.httpRequest({ url })
        .then(function (httpResponse) {
          AccessToken = JSON.parse(httpResponse.text)
          console.log(httpResponse.text)
          AccessToken.expiredAt = new Date().getTime() + (AccessToken.expires_in || 0) * 1000
          _wxGetTicket().then(() => {
            resolve({appId: AccessToken.AppID, access_token: AccessToken.access_token})
          })
        }, function (httpResponse) {
          reject('Request failed with response code ' + httpResponse.status)
        })
    }
  })
}
